extends RigidBody2D

signal hit_zhuankuai # 碰撞到了砖块
signal lost_ball # 小球出界
signal finish_level # 完成本关（砖块全部打完）

export var max_speed = 400
export var speed = 200
var unit_speed = 10


func _ready():
	# 初始给与一个在-135度到-45度之间的随机方向
	randomize()
	var vx = rand_range(-1.0,1.0)
	var vy = -1.0
	linear_velocity = Vector2(vx,vy) * speed

func _on_ball_body_entered(body):
	if body.is_in_group("zhuankuai"):
		body.playSE()
		yield(body,"finishSE")
		body.queue_free()
		emit_signal("hit_zhuankuai")	
	if body is KinematicBody2D:
		# 每次碰撞，增加线速度值
		var speed = linear_velocity.length() # 当前速度值
		var direction:Vector2 = linear_velocity.normalized() # 当前方向
		if speed < max_speed:
			# 计算小球与平板中心之间的距离和夹角
			var d = position.distance_to(body.position)
			speed += d
		# 计算小球与平板中心之间的夹角
		var angle = position.angle_to_point(body.position)
		direction = Vector2.RIGHT.rotated(angle)
#		print(rad2deg(angle))
		linear_velocity = direction * speed
		body.playSE()
		pass 
	if body.is_in_group("wall"):
		var direction:Vector2 = linear_velocity.normalized() # 当前方向
		var angle = position.angle() # 小球与X轴夹角
		if angle < deg2rad(30) or angle > deg2rad(60):
			if direction.y > 0: # 小球正在向下运动
				if direction.x >0: # 右下方
					direction = Vector2.ONE # 45度
				else:# 左下方
					direction = Vector2(-1,1)
			else:# 小球正在向上运动
				if direction.x >0: # 右上方
					direction = Vector2(1,-1) # -45度
				else:# 左上方
					direction = -Vector2.ONE
		linear_velocity = direction * speed
		body.playSE()
	


func _process(delta):
	if position.y >get_viewport_rect().size.y:
		linear_velocity = Vector2.ZERO
		visible = false
		emit_signal("lost_ball")
		set_process(false)
		
#	var size = get_tree().get_nodes_in_group("zhuankuai").size()
#	print(size)
	if get_tree().get_nodes_in_group("zhuankuai").size() == 0:
		emit_signal("finish_level")
		set_process(false)
